package com.celan.year2023.month03.day23;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Celan
 * @ClassName Solution
 * @description: TODO
 * @date 2023/03/23
 * @version: 1.0
 */
public class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] visited;
    int[] nums;
    int n;

    public List<List<Integer>> permuteUnique(int[] nums) {
        this.nums = nums;
        n = nums.length;
        visited = new boolean[n];
        Arrays.sort(nums);
        backTrack(0);
        return res;
    }

    private void backTrack(int idx) {
        if (idx == n) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < n; i++) {
            if (visited[i] || (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1])) {
                continue;
            }
            path.add(nums[i]);
            visited[i] = true;
            backTrack(idx + 1);
            visited[i] = false;
            path.remove(path.size() - 1);
        }
    }
}
